	$.fn.onEnter = function(fn) {  
	
	    return this.each(function() {  
	        $(this).bind('onEnter', fn);
	        $(this).keydown(function(e){
	            if(e.keyCode == 13)
	            {
	              $(this).trigger("onEnter");
	              e.preventDefault();
	            }
	        })
	    });  
	 };
   
    var chart;
	var tasks;
	var procDefs;
	var procInstances;
	
	var user = '';
	
	var currentTask;
	
	var proxyURL = contextPath + '/mvc/proxy'
	
	//var wfServiceUrl = 'http://localhost:8080/activiti-rest/service';
	var wfServiceUrl = 'http://ec2-23-22-173-34.compute-1.amazonaws.com:8080/activiti-rest/service';
   function loadPieChart() {
		 chart = new Highcharts.Chart({
	            chart: {
	                renderTo: 'container',
	                plotBackgroundColor: null,
	                plotBorderWidth: null,
	                plotShadow: false
	            },
	            title: {
	                text: 'Tasks'
	            },
	            tooltip: {
	        	    pointFormat: '{series.name}: <b>{point.y}</b>',
	            	percentageDecimals: 1
	            },
	            plotOptions: {
	                pie: {
	                    allowPointSelect: true,
	                    cursor: 'pointer',
	                    dataLabels: {
	                        enabled: true,
	                        color: '#000000',
	                        connectorColor: '#000000',
	                        formatter: function() {
	                            return '<b>'+ this.point.name +'</b>: '+ this.y;
	                        }
	                    }
	                }
	            },
	            series: [{
	                type: 'pie',
	                name: 'Browser share',
	                data: [
	                    ['All Tasks', 8.0],
	                    {
	                        name: 'My Task',
	                        y: 2.0,
	                        sliced: true,
	                        selected: true
	                    }
	                ]
	            }]
	        });
	 }

function createTaskListDialog() {
	var html = '';
	if (tasks.data.length > 0) {
		html += '<table id="taskListTable" cellpadding="0" cellspacing="0" border="0" class="display dataTable">';
		html += '<thead><tr><th>ID</th><th>View Details</th></thead>';
		html += '<tbody>';
		for (var i = 0; i < tasks.data.length; i++) {
			html += '<tr><td id="' + tasks.data[i].id + '" width="150">' + tasks.data[i].name + 
					'</td><td align="right"><a href="' + contextPath + '/mvc/task/' + tasks.data[i].id + '">View</a></td></tr>';
		}
		html += '</tbody></table>';
	} else {
		html += 'No Task';
	}
	$('#divMyTasksList').html(html);
	$('#taskListTable').dataTable({"aoColumns": [
	                                             { "sWidth": "80%" }, 
	                                             { "sWidth": "" }
	                                         ]});
}

function createProcDefsDialog() {
	var html = '';
	html += '<table id="procDefTable" cellpadding="0" cellspacing="0" border="0" class="display dataTable">';
	html += '<thead><tr><th>ID</th><th>Name</th><th>Start</th></thead>';
	html += '<tbody>';
	for (var i = 0; i < procDefs.data.length; i++) {
		html += '<tr><td>' + procDefs.data[i].id + '</td><td>' + procDefs.data[i].name 
		+ '</td><td align="center"><a href="#" onclick="startProcess(\'' + procDefs.data[i].id +'\')">Start</a></td></tr>';
	}
	html += '</tbody></table>';
	$('#divProcesses').html(html);
	var oTable = $('#procDefTable').dataTable();
	/*
	if ( oTable.length > 0 ) {
		oTable.fnAdjustColumnSizing();
	}*/
}

function createRunningProcInstancesDialog() {
    var html = '';
	html += '<table id="procInstTable" cellpadding="0" cellspacing="0" border="0" class="display dataTable">';
	html += '<thead><tr><th>ID</th><th>Process ID</th><th>Process Name</th><th>Start Time</th><th>Start User</th><th>View Details</th></thead>';
	html += '<tbody>';
	var tmpProcDef;
	for (var i = 0; i < procInstances.data.length; i++) {
		tmpProcDef = getProcessDefById(procInstances.data[i].processDefinitionId);
		html += '<tr><td>' + procInstances.data[i].id + '</td><td> '+ procInstances.data[i].processDefinitionId + '</td><td>' 
		        + ((tmpProcDef == null) ? ' ' : tmpProcDef.name) + '</td><td>' + procInstances.data[i].startTime 
		        + '</td><td>' + procInstances.data[i].startUserId 
		        + '</td><td align="center"><a href="' + contextPath + '/mvc/processInstances/' + procInstances.data[i].id +'/tasks">View</a></td></tr>';
	}
	html += '</tbody></table>';
	$('#divRunningProcInstances').html(html);
	$('#procInstTable').dataTable({
		"sDom": '<f>t<p><"clear">'
	});
}

function createProcInstanceDetailsDialog(procTasks) {
	var html = '<div style="text-align: center;">Task Details for Process Instance ' + procTasks.processInstanceId;
	html += '</div>';
	html += '<table id="procInstTaskTable" cellpadding="0" cellspacing="0" border="0" class="display dataTable">';
	html += '<thead><tr><th>Task ID</th><th>Task Name</th><th>Owner</th><th>Assignee</th><th>Start Time</th><th>Completed</th><th>Complete Time</th></thead>';
	html += '<tbody>';
	
	if (procTasks.tasks != null) {
		for (var i = 0; i < procTasks.tasks.length; i++) {
			html += '<tr><td>' + procTasks.tasks[i].taskId + '</td><td> '+ procTasks.tasks[i].taskName + '</td><td>' 
			        + ((procTasks.tasks[i].owner == null) ? ' ' : procTasks.tasks[i].owner) + '</td><td>' + procTasks.tasks[i].assignee 
			        + '</td><td>' + procTasks.tasks[i].startTime + '</td><td>' + procTasks.tasks[i].completed + '</td><td>' 
			        + ((procTasks.tasks[i].endTime == null) ? '' :procTasks.tasks[i].endTime)
			        + '</td></tr>';
		}
	}
	html += '</tbody></table>';
	$('#divRunningInstanceTasks').html(html);
	$('#procInstTaskTable').dataTable({
		"sDom": '<f>t<p><"clear">'
	});
}
	
function viewTaskDetails(taskId) {
	for (var i = 0; i < tasks.data.length; i++) {
		if (tasks.data[i].id == taskId) {
			getTaskDetail(tasks.data[i]);
			break;
		}
	}
}

function getAllTasks() {
	$.ajax({
		url : proxyURL,
		data : {
			url : wfServiceUrl + "/tasks",
			param : "assignee=" + user + "&size=999",
			user : user
		},
		type : 'GET',
		success : function(res) {
			tasks = eval("(" + res + ")");
			var html = $('#tabTasks').html();
			createTaskListDialog();
		}
	});
}

function getAllProcessesDefinitions(func) {
	$.ajax({
		url : proxyURL,
		data : {
			url : wfServiceUrl + "/process-definitions",
			param : "size=999",
			user : user
		},
		type : 'GET',
		success : function(res) {
			procDefs = eval("(" + res + ")");
			if (func) {
				func();
			}
			createProcDefsDialog();
		}
	});
}

function getAllRunningProcInstances(func) {
	$.ajax({
		url : proxyURL,
		data : {
			url : wfServiceUrl + "/process-instances",
			param : "size=999",
			user : user
		},
		type : 'GET',
		success : function(res) {
			procInstances = eval("(" + res + ")");
			if (func) {
				func();
			}
		}
	});
}

function getTaskById(taskId){
	$.ajax({
		url : proxyURL,
		data : {
			url : wfServiceUrl + "/task/" + taskId,
			user : user
		},
		type : 'GET',
		success : function(res) {
			getTaskDetail(eval("(" + res + ")"));
		}
	});
}

function getTaskDetail(task) {
	$.ajax({
		url : proxyURL,
		data : {
			url : wfServiceUrl + "/form/" + task.id + "/properties",
			user : user
		},
		type : 'GET',
		success : function(res) {
			
			var html = '';
			var dateTimeFields = new Array();
			
			$('#dbTaskListItemDetail').html('');
			
			html += '<table id="taskDetailTable" class="detailTable">';
			html += '<tr><td width="100">ID: </td><td>' + task.id +'</td></tr>';
			html += '<tr><td width="100">Name: </td><td>' + task.name +'</td></tr>';
			html += '<tr><td width="100">Process ID: </td><td>' + task.processInstanceId +'</td></tr>';
			html += '<tr><td>Assignee: </td><td>' + task.assignee +'</td></tr>';
			html += '<tr><td>CreateTime: </td><td>' + task.createTime +'</td></tr>';
			html += '<tr><td>Description: </td><td>' + ((task.description == null) ? '' : task.description) +'</td></tr>';
			html += '<tr><td>Due Date: </td><td>' + ((task.dueDate == null) ? '' : task.dueDate)  +'</td></tr>';
			html += '<tr><td>Priority: </td><td>' + task.priority +'</td></tr>';
			html += '</table>';
			
			$('#dbTaskListItemDetail').html(html);
			form = eval("(" + res + ")");
			
			task.formData = form.data;
			
			currentTask = task;
			
			html = '<div><b>&nbsp;</b></div>';
			html += '<div><b>Fill in the form below and complete the task: </b></div>';
			
			if (task.formData.length > 0) {
				html += '<table class="detailTable">';
				
				for (var i = 0; i < task.formData.length; i++) {
					if (task.formData[i].type == 'date') {
						dateTimeFields.push(task.formData[i].id);
					}
					html += createFieldForFormData(task.formData[i]);
				}
				html += '</table>';
				
			}
			
			html += '<div><b>&nbsp;</b></div>';
			html += '<a href="#" onclick="completeTask(currentTask);">Complete</a>';
			$('#dbTaskListItemDetail').append(html);
			
			
			for (var i = 0; i < dateTimeFields.length; i++) {
				$('#' + dateTimeFields[i]).datetimepicker();
			}
		}
	});
}

function getProcessDefById(procDefId) {
	for (var i = 0; i < procDefs.data.length; i++) {
		if (procDefs.data[i].id == procDefId) {
			return procDefs.data[i];
		}
	}
}

function getProcInstDetails(procInsId) {
	$.ajax({
		url : proxyURL,
		data : {
			url : wfServiceUrl + "/process-instance/" + procInsId ,
			user : user
		},
		type : 'GET',
		success : function(res) {
			createProcInstanceDetailsDialog(eval("(" + res + ")"));
		}
	});
}

function createFieldForFormData(formData) {
    var result = '';
	if (formData.type == 'string' || formData.type == 'long') {
		result = '<tr><td width="100">' + formData.name + ': </td>' + '<td><textarea id="' + formData.id + '" name="' + formData.id + '" rows="4" cols="50">' + ((formData.value == null) ? '' : formData.value) + '</textarea></td></tr>';
	} else if (formData.type == 'boolean') {
		result = '<tr><td width="100">' + formData.name + ': </td>' + '<td><input type="checkbox" id = "' + formData.id + '" name="' + formData.id + '" value="1"></td></tr>';
	} else if (formData.type == 'date') {
		result = '<tr><td width="100">' + formData.name + ': </td>' + '<td><input type="text" name="' + formData.id + '" id="' + formData.id + '" value="' + ((formData.value == null) ? '' : formData.value) + '" /></td></tr>';
	} else if (formData.type == 'enum') {
		
		var options = '';
		for (var i = 0; i < formData.enumValues.length; i++) {
			options = options + '<option value="' + formData.enumValues[i].id+ '">' + formData.enumValues[i].name + '</option>';
		}
		result = '<tr><td width="100">' + formData.name + ': </td>' + 
		        '<td><select>' + options + 
				'</select></td></tr>';
	}
	return result;
}

function fillFrom() {
	var currentForm = new Object();
	
	for (var i = 0; i < currentTask.formData.length; i++) {
		currentForm[currentTask.formData[i].id] = $('#' + currentTask.formData[i].id).val();
	}
	
	return currentForm;
}

function startProcess(procDefId) {
	$.ajax({
		url : proxyURL,
		data : {
			url : wfServiceUrl + "/process-instance",
			jsonParam: '{"processDefinitionId":"' + procDefId + '","businessKey": null}', 
			method: 'POST',
			user : user
		},
		type : 'GET',
		success : function(res) {
			var resp = eval("(" + res + ")");
			if (resp.id != null) {
				alert('Process Started.');
			}
			$('#lnkProcInstances').html('Retriving...');
			getAllRunningProcInstances();
		}
	});
}

function showSwitchUserPanel() {
	$('#divSwitchUserDialog').dialog({height: 140, width: 300});
}

function getUser(func) {
	user = $('#userEmail').val();
	$.ajax({
		url : proxyURL,
		data : {
			url : wfServiceUrl + "/user/" + user,
			errorServlet: '/mvc/createUser',
			method: 'GET',
			user : user
		},
		type : 'GET',
		success : function(res) {
			func();
		},
		error: function(res) {
			//alert('User does not exists!');
		}
	})
}

function refreshUserDashboard() {
	getAllTasks();
	getAllProcessesDefinitions();
	getAllRunningProcInstances();
}